package dao

import (
	"gowork/memberGoKit/model"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"fmt"
)

var (
	db *gorm.DB
	err error
)

func init(){
	db, err = gorm.Open("mysql", "root:new_password@tcp(localhost:3306)/micro_iris_insert")
	if err != nil {
		panic("failed to connect database")
	}
	db.AutoMigrate(&model.ProductType{}, &model.Product{}, &model.ProjectType{}, &model.Project{}, &model.Meal{}, &model.Member{})
}

type MemberDaoImp struct{

}

func (mdi *MemberDaoImp)InesrtDao(mb []*model.Member)map[string]string{
	for _, jv := range mb{
		var m model.Member
		db.Where("id= ?", jv.Id).First(&m)
		if m.Id == 0{
			db.Create(jv)
		}
		for _, mv := range jv.Meallist{
			var ml model.Meal
			db.Where("id= ?", mv.Id).First(&ml)
			if ml.Id == 0{
				db.Create(mv)
			}
			db.Model(jv).Association("Meallist").Append(mv)

			for _, mvj := range mv.ProjectList{
				var jt model.ProjectType
				db.Where("id= ?", mvj.TypeId).First(&jt)
				if jt.Id == 0{
					db.Create(mvj.Type)
				}

				var j model.Project
				db.Where("id= ?", mvj.Id).First(&j)
				if j.Id == 0{
					db.Create(mvj)
				}
				db.Model(mv).Association("ProjectList").Append(mvj)

			}
			for _, mvd := range mv.ProductList{
				var dt model.ProductType
				db.Where("id= ?", mvd.TypeId).First(&dt)
				if dt.Id == 0{
					db.Create(mvd.Type)
				}
				var d model.Product
				db.Where("id= ?", mvd.Id).First(&d)
				if d.Id == 0{
					db.Create(mvd)
				}
				db.Model(mv).Association("ProductList").Append(mvd)
			}
		}
	}
	return map[string]string{"message":"插入成功", "code":"200"}
}


func (mdi *MemberDaoImp)QueryDao() []*model.Member{
	var m []*model.Member
	db.Find(&m)
	fmt.Println(m)
	for _, v := range m{
		db.Joins("JOIN member_meals ON member_meals.meal_id = meals.id AND member_meals.member_id = ?", v.Id).Find(&v.Meallist)

		for _, mv := range v.Meallist{
			db.Joins("JOIN meal_projects ON meal_projects.project_id = projects.id AND meal_projects.meal_id = ?", mv.Id).Find(&mv.ProjectList)

			for _, jv := range mv.ProjectList{
				db.Joins("JOIN projects ON project_types.id = projects.type_id AND projects.id = ?", jv.Id).Find(&jv.Type)
			}
			
			db.Joins("JOIN meal_products ON meal_products.product_id = products.id AND meal_products.meal_id = ?", mv.Id).Find(&mv.ProductList)
		
			for _, dv := range mv.ProductList{
				db.Joins("JOIN products ON product_types.id = products.type_id AND products.id = ?", dv.Id).Find(&dv.Type)

			}	
		}
	}

	return m
}


